package cn.sfa.controller.customer;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import cn.sfa.common.pagination.Pagination;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.DateUtil;
import cn.sfa.common.utils.FormValidate;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.common.SaleHideCustomerCommonEntity;
import cn.sfa.entity.customer.SaleHideCustomer;
import cn.sfa.entity.team.PolicyInfoEntity;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.customer.CustomerService;

/**
 * 
 * 类名称：CustomerIndex 类描述： 客户管理首页管理类 创建人：lenovo 创建时间：2012-2-20 下午8:50:06
 * 修改人：lenovo 修改时间：2012-2-20 下午8:50:06 修改备注：
 * 
 * @version
 */
@Controller
@RequestMapping("/customer/manage/index")
public class CustomerManageController extends WebInitBinderContoller {

	Logger log = LoggerFactory.getLogger(CustomerManageController.class);
	@Autowired
	CustomerService customerService;
	
	

	@RequestMapping
	public String index() {

		return "customer/index";
	}

	/**
	 * 转到添加客户页面
	 * 
	 * @return
	 */
	@RequestMapping("addcustomer")
	public String addCustomer(HttpServletRequest request,SaleHideCustomer customer,
			 ModelMap map) {
		  
		return "customer/addcustomer";
	}

	/**
	 * 添加客户
	 * 
	 * @param customer
	 * @param request
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("add")
	public void add(SaleHideCustomer customer, HttpServletRequest request,HttpServletResponse response,
			ModelMap map
			 ) throws Exception {
		 
		String msg = "";
		int count = 0;

		if (CommonUtil.isEmpty(customer.getCustomerName())) {
			msg = "客户姓名不能为空！";
			count = count + 1;
			
		} else if (CommonUtil.isEmpty(customer.getCustomerAddr())) {
			msg = "客户地址不能为空！";
			count = count + 1;
		}else if (CommonUtil.isEmpty(customer.getCustomerPhone())) {
			msg = "客户电话不能为空！";
			count = count + 1;
		}else if (CommonUtil.isEmpty(customer.getContract())) {
			msg = "联系人不能为空！";
			count = count + 1;
		}else if (CommonUtil.isEmpty(customer.getMobile())) {
			msg = "手机号码不能为空！";
			count = count + 1;
		}
		boolean result = count == 0;
		boolean flag=false;
		if (result) {
			SaleUsersLogin sale = (SaleUsersLogin) request.getSession()
					.getAttribute("user");
			customer.setCreateUid(sale.getSaleUsersLoginId());
			customer.setCreateDate(new Date());
			customer.setUpdateDate(new Date());
			customer.setUpdateId(customer.getCreateUid());

			flag = customerService.addCustomer(customer);
			if (flag) {
				msg = "添加客户成功！";
			 
			} else {
				msg = "添加客户失败！";
			}
		}
		 		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");
 
            JSONObject temp = new JSONObject();
            temp.put("result",result);
            temp.put("msg", msg);
            temp.put("flag", flag);
            PrintWriter out=response.getWriter();
	        out.print(temp.toString());
			out.flush();
			out.close();
	}

	/**
	 * 管理客户页面
	 * 
	 * @param saleNews
	 * @return String
	 */
	@RequestMapping(value = "/getcustomers")
	public String getCustomers(
			@RequestParam(value = "currentPage", required = false) String currentPage,
			SaleHideCustomer customer,
			HttpServletRequest request,
			ModelMap map,
			@RequestParam(value = "beginCreateDate", required = false) String beginCreateDate,
			@RequestParam(value = "endCreateDate", required = false) String endCreateDate )
			throws Exception {
		
		System.out.println("========================name::"+ beginCreateDate);
		int pageIndex;
		try {
			pageIndex = Integer.valueOf(currentPage);
		} catch (Exception ex) {
			pageIndex = 1;
		}
		String agentid=((SaleUsersLogin)request.getSession().getAttribute("user")).getUserAgentId();
		Pagination pagination=null;
		pagination = customerService.searchCustomers(pageIndex, 10, request
				.getContextPath()
				+ "/customer/manage/index/getcustomers?"
				+ "customerName="
				+ CommonUtil.jugeAndFixNull(customer.getCustomerName())
				+ "&contract="
				+ CommonUtil.jugeAndFixNull(customer.getContract())
				+ "&customerType="
				+ CommonUtil.jugeAndFixNull(customer.getCustomerType())
				+ "&beginCreateDate="
				+ (CommonUtil.isEmpty(beginCreateDate) ? "" :  beginCreateDate)
				+ "&endCreateDate="
				+ (CommonUtil.isEmpty(endCreateDate) ? "" :  endCreateDate),customer, 
				beginCreateDate,  endCreateDate);
		map.put("pagination", pagination);
		map.put("customerName", customer.getCustomerName());
		map.put("contract", customer.getContract());
		map.put("customerType", customer.getCustomerType());
		map.put("beginCreateDate", CommonUtil.isEmpty(beginCreateDate) ? ""
				:  beginCreateDate);
		map.put("endCreateDate", CommonUtil.isEmpty(endCreateDate) ? ""
				:  endCreateDate);
	 
		
		map.put("page", pageIndex);

		return "customer/getcustomers";
	}
	
	
	
	/**
	 * 删除客户
	 * @param response
	 * @param saleHideCustomerId
	 * @throws IOException
	 */
	@RequestMapping("/delete/{saleCustomerId}")
	public void delete(HttpServletResponse response,HttpServletRequest request,
			@PathVariable("saleCustomerId") String saleHideCustomerId)
			throws IOException {
		PrintWriter out = response.getWriter();
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");
 
            JSONObject temp = new JSONObject();
            
		boolean flag = customerService.deleteCustomerById(saleHideCustomerId);
		temp.put("result",flag);
        out.print(temp.toString());
		out.flush();
		out.close();
	}

	/**
	 * 转到修改客户页面
	 * 
	 * @return
	 */
	@RequestMapping("/updatecustomer/{saleCustomerId}")
	public String updateCustomer(ModelMap map, HttpServletRequest request,
			@PathVariable("saleCustomerId") String saleHideCustomerId) {
		SaleHideCustomer customer = customerService
				.getCustomer(saleHideCustomerId);
		map.put("customer", customer);
		return "customer/updatecustomer";
	}

	/**
	 * 编辑客户
	 * 
	 * @param customer
	 * @param request
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("update")
	public void update(SaleHideCustomer customer, HttpServletRequest request,HttpServletResponse response,
			ModelMap map ) throws Exception {
		 
		String msg = "";
		int count = 0;

		if (CommonUtil.isEmpty(customer.getCustomerName())) {
			msg = "客户姓名不能为空！";
			count = count + 1;
			
		} else if (CommonUtil.isEmpty(customer.getCustomerAddr())) {
			msg = "客户地址不能为空！";
			count = count + 1;
		}else if (CommonUtil.isEmpty(customer.getCustomerPhone())) {
			msg = "客户电话不能为空！";
			count = count + 1;
		}else if (CommonUtil.isEmpty(customer.getContract())) {
			msg = "联系人不能为空！";
			count = count + 1;
		}else if (CommonUtil.isEmpty(customer.getMobile())) {
			msg = "手机号码不能为空！";
			count = count + 1;
		}
		boolean result = count == 0;
		boolean flag=false;
		if (result) {
			SaleUsersLogin sale = (SaleUsersLogin) request.getSession()
					.getAttribute("user");
			customer.setUpdateDate(new Date());
			customer.setUpdateId(sale.getSaleUsersLoginId());

			flag = customerService.updateCustomer(customer);
			if (flag) {
				msg = "修改客户成功！";
				 
			} else {
				msg = "修改客户失败！";
			}
		}
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");
 
            JSONObject temp = new JSONObject();
            temp.put("result",result);
            temp.put("msg", msg);
           
            temp.put("flag", flag);
            PrintWriter out=response.getWriter();
	        out.print(temp.toString());
			out.flush();
			out.close();
	}

	  
	
	/**
	 * 客户详情
	 * @param request
	 * @param model
	 * @param customerID
	 * @return
	 */
	@RequestMapping(value = "/show")
	public String show(
			HttpServletRequest request,
			ModelMap model,
			@RequestParam(value = "saleCustomerId", required = false) String saleCustomerId) {
		  
		 SaleHideCustomer customer=customerService.getCustomer(saleCustomerId);
		 model.put("customer", customer);
		return "customer/show";
	}
	

}
